<template>
  <div class="add-preference-page">
    <div class="from-container">
      <h1>新增用户喜好</h1>
      <form @submit.prevent="handleSubmit">
        <!-- <div class="form-group">
          <label>自增ID:</label>
          <input v-model="form.Id" required>
        </div> -->
        <div class="form-group">
          <label>用户ID:</label>
          <input v-model="form.userId" required>
        </div>
        <div class="form-group">
          <label>标签名称:</label>
          <select v-model="form.tag" required>
            <option v-for="tag in tags" :key="tag" :value="tag">{{ tag }}</option>
          </select>
        </div>
        <div class="form-group">
          <label>喜好占比:</label>
          <input v-model="form.percentage" type="number" min="1" max="100" required>%
        </div>
        <button type="submit" class="submit-btn" >提交</button>
        <router-link to="/user-preference" class="cancel-btn">取消</router-link>
        <router-link to="/user-preference" class="cancel-btn">返回</router-link>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import Service from '@/router/interceptor.js';  // 新增导入封装的axios实例
const router = useRouter()
const tags = ['科技', '娱乐', '教育', '游戏', '音乐', '体育']
const form = ref({
  userId: '',
  tag: '科技',
  percentage: ''
})

const handleSubmit = async () => {
  try {
    const params = new URLSearchParams();
    const tpercentValue = (parseFloat(form.value.percentage) / 100).toFixed(2);
    params.append("tname", form.value.tag);
    params.append('tpercent', tpercentValue);
    params.append("uid", form.value.userId);
    const response = await Service.post('/api/userFlavor/add', params,{
      // 参数名需要与Java Bean字段完全匹配
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded' 
      }
    });

    if (response.code === 200) {
      ElMessage.success('喜好添加成功');
      router.push('/user-preference');
    }
  } catch (error) {
    const errorMessage = error.response?.data?.info 
      || error.response?.data?.message 
      || error.message 
      || '请求失败';
    ElMessage.error(errorMessage);
  }
};
</script>

<style scoped>
.add-preference-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 110vh;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: inline-block;
  width: 80px;
  font-weight: bold;
}

input, select {
  padding: 8px;
  width: 200px;
}

.submit-btn {
  background-color: #4CAF50;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.cancel-btn {
  padding: 9px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-decoration: none;
  color: #333;
}
</style>